<?php
declare (strict_types = 1);

namespace app\common\middleware\http;
use app\common\exception\ControllerExtendException;
use adminmatrix\server\app\AdminMatrix;
class InitMiddleware
{
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle($request, \Closure $next)
    {
        //获取控制器
        try {
            $app = App()->http->getName();
            $controller = str_replace('.', '\\', $request->controller());
            $controller = "\\app\\{$app}\\controller\\{$controller}Controller";
            $controllerClass = invoke($controller);
            if (($controllerClass instanceof AdminMatrix) === false) {
                throw new ControllerExtendException($controller, '404');
            }
        } catch (ClassNotFoundException $e) {
            throw new HttpException(404, 'controller not exists:' . $e->getClass());
        }

        //创建控制器对象
        $request->controllerObject = invoke($controller);

        return $next($request);

    }
}
